package com.zzy.algorithm.linkedList;

import com.zzy.algorithm.model.ListNode;

/**
 *  LeetCode - 21 : 合併两个有序链表
 *
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class Q7_MergeTwoOrderLinkedList {

    public static void main(String[] args) {
        Q7_MergeTwoOrderLinkedList q7_mergeTwoOrderLinkedList = new Q7_MergeTwoOrderLinkedList();
        ListNode solution = q7_mergeTwoOrderLinkedList.solution2(ListNode.list1, ListNode.list2);
        while (solution != null){
            System.out.println(solution.val);
            solution = solution.next;
        }
    }

    /**
     * 递归
     * @param list1
     * @param list2
     * @return
     */
    public ListNode solution(ListNode list1,ListNode list2){
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        if(list1.val > list2.val){
            list2.next = solution(list1,list2.next);
            return list2;
        } else {
            list1.next = solution(list1.next,list2);
            return list1;
        }

    }


    /**
     * 迭代
     * @param list1
     * @param list2
     * @return
     */
    public ListNode solution2(ListNode list1,ListNode list2){
        ListNode result = new ListNode(-1);
        ListNode node = result;
        while(list1 != null || list2 != null){
            if(list1 == null){
                node.next = list2;
                break;
            }
            if(list2 == null){
                node.next = list1;
                break;
            }
            if(list1.val < list2.val){
                node.next = list1;
                list1 = list1.next;
            } else {
                node.next = list2;
                list2 = list2.next;
            }
            node = node.next;
        }
        return result.next;
    }

}
